﻿using Autofac;
using DongFangGuoKai.WMSPlatform.Core;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyModel;
using SqlSugar;
using System.Reflection;
using System.Runtime.Loader;

namespace DongFangGuoKai.WMSPlatform.WebApi.Utility.DI
{
    /// <summary>
    /// Autofa默认瞬时
    /// Controller支持了属性注入
    /// </summary>
    public class ApiModule : Autofac.Module
    {
        protected override void Load(ContainerBuilder builder)
        {
            //获取所有创建的项目lib
            var libs = DependencyContext.Default
                .CompileLibraries
                .Where(x => !x.Serviceable && x.Type == "project")
                .ToList();

            //将lib转为Assembly
            List<Assembly> assemblies = new();
            foreach (var lib in libs)
            {
                var assemblyName = new AssemblyName(lib.Name);
                var assembly = AssemblyLoadContext.Default.LoadFromAssemblyName(assemblyName);
                assemblies.Add(assembly);
            }

            //服务注册并区分生命周期

            //瞬时
            builder.RegisterAssemblyTypes(assemblies.ToArray())
                   .Where(x => x.FullName.StartsWith("DongFangGuoKai.WMSPlatform.Service") && x.Name.EndsWith("Service"))
                   .AsSelf().AsImplementedInterfaces().PropertiesAutowired();

            //注入ApiService
            builder.RegisterAssemblyTypes(assemblies.ToArray())
                   .Where(x => x.FullName.StartsWith("DongFangGuoKai.WMS.ApiService") && x.Name.EndsWith("Service"))
                   .AsSelf().AsImplementedInterfaces();

            // 注册ControllerBase
            Type[] controllersTypeAssembly = typeof(Program).Assembly.GetExportedTypes()
            .Where(type => typeof(ControllerBase).IsAssignableFrom(type)).ToArray();
            builder.RegisterTypes(controllersTypeAssembly).PropertiesAutowired();

        }
    }
}
